<?php
namespace app\api\service;
use think\Controller;
use think\Db;

class Dealer extends Controller {
    static protected $err_code = 0;
    //申请成为经销商接口
    static public function dealer_create($param) {
        if( !isset($param['id']) || !isset($param['member_id']) || !isset($param['proposer']) || !isset($param['card_no'])
            || !isset($param['id_card_front']) || !isset($param['id_card_verso']) || !isset($param['id_card_in_hand'])
            || !isset($param['level']) || !isset($param['province']) || !isset($param['city']) || !isset($param['area']) || !isset($param['street'])
            || !isset($param['duty_province']) || !isset($param['duty_city']) || !isset($param['duty_area']) || !isset($param['address'])
            || !isset($param['lat'])  || !isset($param['lon'])
            || !isset($param['business_license_name'])  || !isset($param['business_license_num']) || !isset($param['business_license'])
            || !isset($param['cover']) || !isset($param['phone'])
            || !isset($param['logo']) || !isset($param['collecting_note']) || !isset($param['dealer_name'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{
            /*调用验证器 验证数据*/
            $validate = validate('Dealer');
            //判断是否可以申请

            if (!$validate->check($param)) {
                self::$err_code = $validate->getError();
                throw new \Exception('提交资料不完整，请确认');
            }

            // 根据地址名称获取地址ID
            $scope = get_scope_id($param['province'], $param['city'], $param['area'], $param['street']);

            $data = [
                'member_id' => $param['member_id']
                ,'dealer_name' => $param['dealer_name']
                ,'proposer' => $param['proposer']
                ,'card_no' => $param['card_no']
                ,'level' => $param['level']

                ,'province' => $scope['province']
                ,'city' => $scope['city']
                ,'area' => $scope['area']
                ,'street' => $scope['street']

                ,'address' => $param['address']
                ,'lat' => $param['lat']
                ,'lon' => $param['lon']
                ,'business_license_name' => $param['business_license_name']
                ,'business_license_num' => $param['business_license_num']
                ,'apply_time' => time()
                ,'id_card_in_hand' => $param['id_card_in_hand']
                ,'id_card_front' => $param['id_card_front']
                ,'id_card_verso' => $param['id_card_verso']
                ,'cover' => $param['cover']
                ,'phone' => $param['phone']
                ,'business_license' => $param['business_license']
                ,'logo' => $param['logo']
                ,'collecting_note' => $param['collecting_note']
                ,'audit_status' => 1
            ];

            if (!isset($param['environment_img1']) || !isset($param['environment_img2']) || !isset($param['environment_img3']) ||
                !isset($param['environment_img4']) || !isset($param['environment_img5'])) {
                self::$err_code = 400093;
                throw new \Exception('FAULT');
            }
            $data['environment_img1'] = isset($param['environment_img1']) ? $param['environment_img1'] : '';
            $data['environment_img2'] = isset($param['environment_img2']) ? $param['environment_img2'] : '';
            $data['environment_img3'] = isset($param['environment_img3']) ? $param['environment_img3'] : '';
            $data['environment_img4'] = isset($param['environment_img4']) ? $param['environment_img4'] : '';
            $data['environment_img5'] = isset($param['environment_img5']) ? $param['environment_img5'] : '';

            $id = $param['id'];

            $duty_data = [
                'province' => $param['duty_province'],
                'city' => $param['duty_city'],
                'area' => $param['duty_area'],
                'level' => $param['level']
            ];



            if ($id > 0) {
//                Db::listen(function($sql, $time, $explain){
//                    // 记录SQL
//                    echo $sql;
//                });

                Db::table('mob_dealer')->where('id', $id)->update($data);
                // 更新负责区域数据
                Db::table('mob_duty_area')->where('member_id', $param['member_id'])->where('member_type', 2)->update($duty_data);

                Db::table('mob_audit_log')->where('obj_id', $id)->where('model', 'dealer')->delete(); // 重新提交  删除审核记录
            } else {

                // 新增记录 先检查是否存在信息相同的经销商店（店铺名字，身份证，用户）
                $check_repair_name = Db::table('mob_dealer')->field('id')->where('dealer_name', $param['dealer_name'])->find();
                if ($check_repair_name) {
                    self::$err_code = 400050;  //店铺名字重复
                    throw new \Exception('FAULT');
                }
                $check_repair_name = Db::table('mob_dealer')->field('id')->where('member_id', $param['member_id'])->find();
                if ($check_repair_name) {
                    self::$err_code = 400052;  //用户已申请维修店
                    throw new \Exception('FAULT');
                }
                $check_repair_name = Db::table('mob_dealer')->field('id')->where('card_no', $param['card_no'])->find();
                if ($check_repair_name) {
                    self::$err_code = 400064;  //身份证号码已申请维修店
                    throw new \Exception('FAULT');
                }

                $id = Db::table('mob_dealer')->insertGetId($data);
                // 组装负责区域数据
                $duty_data['member_id'] = $param['member_id'];
                $duty_data['member_type'] = 2;
                Db::table('mob_duty_area')->insertGetId($duty_data);
            }
            $audit_data = [
                'obj_id' => $id,
                'model' => 'dealer',
                'audit_status' => 1,
                'audit_time' => time()
            ];
            Db::table('mob_audit_log')->insert($audit_data);  // 增加审核记录   已提交
            Db::commit();
            return ['data'=>['dealer_id' => $id],'code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    //审核经销商接口
    static public function dealer_audit($param) {
        if( !isset($param['member_id']) || !isset($param['dealer_id'])
            || !isset($param['auditor']) || !isset($param['audit_status'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{
            $data = [
                'auditor' => $param['auditor']
                ,'audit_status' => $param['audit_status']
                ,'audit_time' => time()
            ];
            Db::table('mob_dealer')->where("id",$param['dealer_id'])->update($data);
            Db::commit();
            return ['data'=>'','code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }

    }

    // 获取经销商信息接口
    static public function get_dealer_info($param) {
        if(!isset($param['dealer_id']) )  return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try {
            $where = ['id' => $param['dealer_id']];
            $dealer = Db::table('mob_dealer')->where($where)->find();

            // 获取维修店地址
            $region = db('region')->where('region_id', 'in', [$dealer['province'], $dealer['city'], $dealer['area'], $dealer['street']])->order('region_id asc')->select();
            $address = '';
            foreach ($region as $r) {
                $address .= $r['region_name'];
            }
            $dealer['address'] = $address.$dealer['address'];

            // 获取负责区域数据
            $duty_area = db('duty_area')->where('member_id', $dealer['member_id'])->where('member_type', 2)->find();

            $duty_area_region = db('region')->where('region_id', 'in', [$duty_area['province'], $duty_area['city'], $duty_area['area'], $duty_area['street']])->order('region_id asc')->select();

            $i = 0;
            $duty_area_name = '';
            foreach ($duty_area_region as $r) {
                $duty_area_name .= $r['region_name'];
                $i++;
                if ($i == $duty_area['level']) {
                    break;
                }
            }
            $dealer['duty_area_name'] = $duty_area_name;

            return ['data' => $dealer, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 获取经销商首页信息
    static public function dealer_index_data($param) {
        if(!isset($param['member_id']) )  return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $where = ['member_id' => $param['member_id']];
            $dealer = Db::table('mob_dealer')->where($where)->find();
            return ['data'=>$dealer, 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }


}





